#!/usr/bin/perl
# -*- mode: perl; -*-
#
# Author: Jim Turner <jim@nukethemfromorbit.com>
#
# Converts an IP into an integer and back again.
#
############################################################
use Getopt::Std;
getopts( 'd:e:h' ) or _help( 'invalid args' );
_help() if( $opt_h );

if( !$opt_d && !$opt_e )
{
    _help( '-d or -e is required' );
}

$asplit = 16777216;
$bsplit = 65536;
$csplit = 256;

if( $opt_d )
{
    my $quad_1 = int( $opt_d / $asplit );
    $q1Temp    = ( $opt_d - ( $quad_1 * $asplit ) );

    my $quad_2 = int( $q1Temp / $bsplit );
    $q2Temp    = ( $q1Temp - ( $quad_2 * $bsplit ) );

    my $quad_3 = int( $q2Temp / $csplit );
    $q3Temp    = ( $q2Temp - ( $quad_3 * $csplit ) );

    my $quad_4 = $q3Temp;

    print "$opt_d converted: $quad_1.$quad_2.$quad_3.$quad_4\n";
}
else
{
    # not the best regex for finding IP addresses, but it mostly works.
    _help( 'That doesn\'t look like an IP address' ) if( $opt_e !~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ );

    my( $a, $b, $c, $d ) = split( /\./, $opt_e );
    my $int_ip = ($a * $asplit) + ($b * $bsplit) + ($c * $csplit) + $d;

    print "$opt_e converted: $int_ip\n";
}

############################################################

sub _help
{
    my $error = shift;

    print "\n$error\n\n" if( $error );

    print << "ENDofHELP";
Usage: IPConverter.pl -d #########|-e ip address [-h]
    
    -d -> a number to convert into an IP address
    -e -> an IP address to convert into a number
    -h -> this message

ENDofHELP

    exit();
}
############################################################
